package com.woke.addressactivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.BaseResponse;
import com.http.HttpMethods;
import com.woke.data.BusinessCategory;
import com.woke.data.Category;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MerchantsActivity extends Activity {

    private EditText edit1, edit2, edit3, edit4, edit6, edit8, edit10, edit11,
            edit12, edit13, edit14, edit15;
    private TextView butOK;
    //	private Spinner mPayWaySpinner,
    private Spinner mCategorySpinner;
    private MyApp myapp;
    private List<String> list;

    private int mPayWay = -1;//1微信 2支付宝
    private String mCategoryCode;

    private String merchantName, shortName, merchantAddress, servicePhone,
            contactName, contactMobile, idCard, accNo, accName, bankType,
            remark;
    private ImageView image_back;
    private RelativeLayout mBar;
    private Intent intent;
    private List<String> mItems = new ArrayList<>();
    private ArrayAdapter<String> mPayWayAdapter;
    private List<BusinessCategory> mBusinessCategorys = new ArrayList<>();
    private ArrayAdapter<String> mCategoryAdapter;
    private List<Category> mCategorys = new ArrayList<>();
    private List<String> mCategoryNames = new ArrayList<>();
    private TextView mPayWayTv;

    // 商户入驻
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchants);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        intent = getIntent();
        if (intent != null) {
            mPayWay = intent.getIntExtra("payway", 1);
        }
        myapp = (MyApp) getApplication();
//		mPayWaySpinner = (Spinner) findViewById (R.id.pay_way_sp);


        mCategorySpinner = (Spinner) findViewById(R.id.spinner2);
        mPayWayTv = (TextView) findViewById(R.id.pay_way_tv);
        if (mPayWay == 1) {
            mPayWayTv.setText(getResources().getString(R.string.title_wechat_pay));
        } else if (mPayWay == 2) {
            mPayWayTv.setText(getResources().getString(R.string.title_alibaba_pay));
        } else if (mPayWay == 3) {
            mPayWayTv.setText(getResources().getString(R.string.title_union_pay));
        }
        edit1 = (EditText) findViewById(R.id.edit1);
        edit2 = (EditText) findViewById(R.id.edit2);
        edit3 = (EditText) findViewById(R.id.edit3);
        edit4 = (EditText) findViewById(R.id.edit4);
        // edit5 = (EditText) findViewById(R.id.edit5);
        edit6 = (EditText) findViewById(R.id.edit6);
        // edit7 = (EditText) findViewById(R.id.edit7);
        edit1 = (EditText) findViewById(R.id.edit1);
        edit8 = (EditText) findViewById(R.id.edit8);
        edit10 = (EditText) findViewById(R.id.edit10);
        // edit11 = (EditText) findViewById(R.id.edit11);
        edit12 = (EditText) findViewById(R.id.edit12);
        edit13 = (EditText) findViewById(R.id.edit13);
        edit14 = (EditText) findViewById(R.id.edit14);
        edit15 = (EditText) findViewById(R.id.edit15);
        butOK = (TextView) findViewById(R.id.avmywalletcard_ok);
        mBar = (RelativeLayout) findViewById(R.id.avuserinfo_frame);

        image_back = (ImageView) findViewById(R.id.avmywalletcard_image_back);

        image_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });

//		mPayWaySpinner.setOnItemSelectedListener (new OnItemSelectedListener () {
//
//
//			@Override
//			public void onItemSelected(AdapterView<?> arg0, View arg1,
//					int arg2, long arg3) {
//
//				BusinessCategory businessCategory = mBusinessCategorys.get (arg2);
//				mPayWay = businessCategory.getPayway ();
//				List<Category> categoryList = businessCategory.getCategory ();
//				if (categoryList != null) {
//					mCategorys.clear ();
//					mCategorys.addAll (categoryList);
//					mCategoryNames.clear ();
//					for (Category category : mCategorys) {
//						mCategoryNames.add (category.getCategoryname ());
//					}
//					if (mCategoryAdapter == null) {
//						mCategoryAdapter = new ArrayAdapter<String> (MerchantsActivity.this, android.R.layout.simple_spinner_item, mCategoryNames);
//						mCategoryAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
//						mCategorySpinner.setAdapter (mCategoryAdapter);
//					} else {
//						mCategoryAdapter.notifyDataSetChanged ();
//					}
//				}
//
//			}
//
//			@Override
//			public void onNothingSelected(AdapterView<?> arg0) {
//				// TODO Auto-generated method stub
//
//			}
//
//		});
        mCategorySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position < mCategorys.size()) {
                    mCategoryCode = mCategorys.get(position).getCategorycode();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        butOK.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                merchantName = edit1.getText().toString();// 商户名称,要求与营业执照上的名称一致
                shortName = edit2.getText().toString();// 商户简称
                merchantAddress = edit3.getText().toString();// 商户地址
                servicePhone = edit4.getText().toString();// 客服电话
                // orgCode = edit5.getText().toString();// 组织机构代码
                contactName = edit6.getText().toString();// 联系人名称
                contactMobile = edit8.getText().toString();// 联系人手机号
                idCard = edit10.getText().toString();// 商户身份证信息
                // merchantLicense = edit11.getText().toString();// 商户营业执照号
                accNo = edit12.getText().toString();// 收款人账户号
                accName = edit13.getText().toString();// 收款人账户名
                bankType = edit14.getText().toString();// 收款人账户联行号
                remark = edit15.getText().toString();// 备注说明


                if (null == merchantName || merchantName.equals("")) {

                    Toast.makeText(MerchantsActivity.this, "商户名称不能为空", Toast.LENGTH_SHORT).show();
                } else if (null == shortName || shortName.equals("")) {
                    Toast.makeText(MerchantsActivity.this, "商户简介不能为空", Toast.LENGTH_SHORT).show();
                } else if (null == merchantAddress || merchantAddress.equals("")) {
                    Toast.makeText(MerchantsActivity.this, "商户地址不能为空", Toast.LENGTH_SHORT).show();
                } else if (null == servicePhone || servicePhone.equals("")) {

                    Toast.makeText(MerchantsActivity.this, "客服电话不能为空", Toast.LENGTH_SHORT).show();
                } else if (null == idCard || idCard.equals("")) {
                    Toast.makeText(MerchantsActivity.this, "商户身份证信息", Toast.LENGTH_SHORT).show();
                } else if (null == accNo || accNo.equals("")) {
                    Toast.makeText(MerchantsActivity.this, "收款人账户号", Toast.LENGTH_SHORT).show();
                } else if (null == accName || accName.equals("")) {
                    Toast.makeText(MerchantsActivity.this, "收款人账户名", Toast.LENGTH_SHORT).show();
                } else if (null == bankType || bankType.equals("")) {
                    Toast.makeText(MerchantsActivity.this, "收款人账户开户行", Toast.LENGTH_SHORT).show();
                } else {

				/*
                 * final String payWay = "1"; final String merchantName =
				 * "厦门中财在线网络科技有限公司";// 商户名称,要求与营业执照上的名称一致 final String shortName
				 * = "中财在线";// 商户简称 final String merchantAddress =
				 * "福建省厦门市思明区厦禾路772号乐创园B幢一层之二";// 商户地址 final String servicePhone
				 * = "4006080608";// 客服电话 final String orgCode = "79809948-3";//
				 * 组织机构代码 final String contactName = "曹福州";// 联系人名称 final String
				 * contactPhone = "0592-2111818";// 联系人电话 final String
				 * contactMobile = "13799787899";// 联系人手机号 final String
				 * contactEmail = "139787899@qq.com";// 联系人邮箱 final String
				 * idCard = "350403197103196011";// 商户身份证信息 final String
				 * merchantLicense = "350203200148328";// 商户营业执照号 final String
				 * accNo = "6214855920216849";// 收款人账户号 final String accName =
				 * "曹福州";// 收款人账户名 final String bankName = "招商银行厦门分行营业部";//
				 * 收款人账户联行号 final String remark = "123";// 备注说明 final String
				 * cateid = "290";// 备注说明
				 */
                /*
                 * dopost(type, "厦门中财在线网络科技有限公司", "中财在线",
				 * "福建省厦门市思明区厦禾路772号乐创园B幢一层之二", "4006080608", "79809948-3",
				 * "曹福州", "0592-2111818", "13799787899", "139787899@qq.com",
				 * cateid, "350403197103196011", "350203200148328",
				 * "6214855920216849", "曹福州", "招商银行厦门分行营业部", "123");
				 */
                    mBar.setVisibility(View.VISIBLE);
                    dopost(mPayWay, merchantName, shortName, merchantAddress,
                            servicePhone, contactName, contactMobile, mCategoryCode,
                            idCard, accNo, accName, bankType, remark);


                }

            }

        });
        getPayWayAndCategory();
    }

    /**
     * 获取支付类型和经营栏目
     */
    private void getPayWayAndCategory() {
//		Datas_load datasLoad = MyApp.getInstance ().getDatas_load ();
//		if (datasLoad == null) return;
//		HttpMethods.getInstance ()
//				.getPayway (mCategoryObserver, Integer.parseInt (datasLoad.getId ()));
        HttpMethods.getInstance().getBusinessCategory(mBCategoryObserver, mPayWay);
    }

    //	private Observer<List<BusinessCategory>> mCategoryObserver = new Observer<List<BusinessCategory>> () {
//
//
//		@Override
//		public void onSubscribe(Disposable d) {
//
//		}
//
//		@Override
//		public void onNext(List<BusinessCategory> value) {
//			if (value != null && value.size () > 0) {
//				mBusinessCategorys.clear ();
//				mBusinessCategorys.addAll (value);
//				mItems.clear ();
//				for (int i = 0; i < value.size (); i++) {
//					mItems.add (value.get (i).getName ());
//				}
//
//				if (mPayWayAdapter == null) {
//					mPayWayAdapter = new ArrayAdapter<> (MerchantsActivity.this, android.R.layout.simple_spinner_item, mItems);
//					mPayWayAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
//					mPayWaySpinner.setAdapter (mPayWayAdapter);
//				} else {
//					mPayWayAdapter.notifyDataSetChanged ();
//				}
//
//			}
//		}
//
//		@Override
//		public void onError(Throwable e) {
//			Toast.makeText (MerchantsActivity.this, e.getMessage (), Toast.LENGTH_SHORT).show ();
//		}
//
//		@Override
//		public void onComplete() {
//
//		}
//	};
    private Observer<List<Category>> mBCategoryObserver = new Observer<List<Category>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<Category> categoryList) {


            if (categoryList != null) {
                mCategorys.clear();
                mCategorys.addAll(categoryList);
                mCategoryNames.clear();
                for (Category category : mCategorys) {
                    mCategoryNames.add(category.getCategoryname());
                }
                if (mCategoryAdapter == null) {
                    mCategoryAdapter = new ArrayAdapter<String>(MerchantsActivity.this, android.R.layout.simple_spinner_item, mCategoryNames);
                    mCategoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    mCategorySpinner.setAdapter(mCategoryAdapter);
                } else {
                    mCategoryAdapter.notifyDataSetChanged();
                }
            }

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private void dopost(int payWap, String merchantName, String shortName,
                        String merchantAddress, String servicePhone, String contactName,
                        String contactMobile, String category, String idCard, String accNo,
                        String accName, String bankName, String remark) {
        // 封装数据
        if (myapp.getDatas_load() == null) return;
        mBar.setVisibility(View.VISIBLE);
        HttpMethods.getInstance()
                .merchantInfo(mCommitMerchantsObserver, Integer.parseInt(myapp.getDatas_load()
                        .getId()), payWap, merchantName, shortName, merchantAddress, servicePhone, contactName, contactMobile, category, idCard, accNo, accName, bankName, remark);
//		Map<String, String> parmas = new HashMap<String, String> ();
//		parmas.put ("userId", myapp.getDatas_load ().getId ());
//		parmas.put ("payWay", payWap);
//		parmas.put ("merchantName", merchantName);
//		parmas.put ("shortName", shortName);
//		parmas.put ("merchantAddress", merchantAddress);
//		parmas.put ("servicePhone", servicePhone);
//		parmas.put ("contactName", contactName);
//		parmas.put ("contactMobile", contactMobile);
//		parmas.put ("category", category);
//		parmas.put ("idCard", idCard);
//		parmas.put ("accNo", accNo);
//		parmas.put ("accName", accName);
//		parmas.put ("bankName", bankName);
//		parmas.put ("remark", remark);

//		System.out.println (parmas);
//
//		DefaultHttpClient client = new DefaultHttpClient ();// http客户端
//		HttpPost httpPost = new HttpPost (Contants.BASEURL
//				+ "g=api&m=Scancode&a=merchantSettled");
//
//		ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair> ();
//		if (parmas != null) {
//			Set<String> keys = parmas.keySet ();
//			for (Iterator<String> i = keys.iterator (); i.hasNext (); ) {
//				String key = (String) i.next ();
//				pairs.add (new BasicNameValuePair (key, parmas.get (key)));
//			}
//		}
//
//		try {
//			UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity (pairs,
//					"utf-8");
//			/*
//			 * 将POST数据放入HTTP请求
//			 */
//			httpPost.setEntity (p_entity);
//			/*
//			 * 发出实际的HTTP POST请求
//			 */
//			HttpResponse response = client.execute (httpPost);
//			HttpEntity entity = response.getEntity ();
//			InputStream content = entity.getContent ();
//			String returnConnection = convertStreamToString (content);
//
//			System.out.println ("returnConnection============="
//					+ returnConnection);
//			System.out.println ("response------------------" + response);
//			try {
//				JSONObject jsonObject = new JSONObject (returnConnection);
//				final String flag = jsonObject.getString ("flag");
//				final String info = jsonObject.getString ("info");
//				System.out.println (info);
//
//				if (flag.equals ("success")) {
//					JSONObject json = jsonObject.getJSONObject ("data");
//
//					mBar.setVisibility (View.GONE);
//					Toast.makeText (MerchantsActivity.this, "商户入驻成功！！！",
//							Toast.LENGTH_SHORT).show ();
//					setResult (666, intent);
//					finish ();
//
//				} else {
//
//					mBar.setVisibility (View.GONE);
//					Toast.makeText (MerchantsActivity.this, info,
//							Toast.LENGTH_SHORT).show ();
//
//
//				}
//
//			} catch (JSONException e) {
//				// TODO Auto-generated catch block
//
//				e.printStackTrace ();
//			}
//
//		} catch (IllegalStateException e) {
//			e.printStackTrace ();
//		} catch (IOException e) {
//			e.printStackTrace ();
//		}


    }


//	private String convertStreamToString(InputStream content) {
//		// TODO Auto-generated method stub
//		BufferedReader reader = new BufferedReader (new InputStreamReader (
//				content));
//		StringBuilder sb = new StringBuilder ();
//		String line = null;
//		try {
//			while ((line = reader.readLine ()) != null) {
//				sb.append (line);
//			}
//		} catch (IOException e) {
//			e.printStackTrace ();
//		} finally {
//			try {
//				content.close ();
//			} catch (IOException e) {
//				e.printStackTrace ();
//			}
//		}
//		return sb.toString ();
//	}

    private Observer<BaseResponse> mCommitMerchantsObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {

            if (value != null) {
                if (value.resultSuccess()) {

                    mBar.setVisibility(View.GONE);
                    Toast.makeText(MerchantsActivity.this, "商户入驻成功！！！",
                            Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().post(mPayWay);
                    finish();
                } else {
                    Toast.makeText(MerchantsActivity.this, value.getInfo(),
                            Toast.LENGTH_SHORT).show();
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            mBar.setVisibility(View.GONE);
        }

        @Override
        public void onComplete() {
            mBar.setVisibility(View.GONE);
        }
    };

}
